"""
创建 document_shares 表
"""
import sys
import os

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from sqlalchemy import text
from app.models.database import engine
from loguru import logger

logger.add("logs/create_table.log", rotation="1 day", level="INFO")


def create_document_shares_table():
    """创建 document_shares 表"""
    print("=" * 80)
    print("创建 document_shares 表")
    print("=" * 80)
    
    try:
        with engine.connect() as conn:
            # 检查表是否已存在
            check_sql = text("""
                SELECT EXISTS (
                    SELECT FROM information_schema.tables 
                    WHERE table_name = 'document_shares'
                )
            """)
            result = conn.execute(check_sql)
            exists = result.fetchone()[0]
            
            if exists:
                print("✓ document_shares 表已存在")
                logger.info("document_shares 表已存在")
                return
            
            # 创建表
            create_sql = text("""
                CREATE TABLE document_shares (
                    id VARCHAR(36) PRIMARY KEY,
                    document_id VARCHAR(36) NOT NULL,
                    shared_by_id VARCHAR(36) NOT NULL,
                    shared_to_id VARCHAR(36) NOT NULL,
                    permission VARCHAR(20) NOT NULL DEFAULT 'view',
                    expires_at TIMESTAMP,
                    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                    CONSTRAINT fk_document_shares_document 
                        FOREIGN KEY (document_id) 
                        REFERENCES documents(id) 
                        ON DELETE CASCADE,
                    CONSTRAINT fk_document_shares_shared_by 
                        FOREIGN KEY (shared_by_id) 
                        REFERENCES users(id),
                    CONSTRAINT fk_document_shares_shared_to 
                        FOREIGN KEY (shared_to_id) 
                        REFERENCES users(id),
                    CONSTRAINT chk_permission 
                        CHECK (permission IN ('view', 'download', 'comment'))
                );
                
                CREATE INDEX idx_document_shares_document_id ON document_shares(document_id);
                CREATE INDEX idx_document_shares_shared_to_id ON document_shares(shared_to_id);
            """)
            
            conn.execute(create_sql)
            conn.commit()
            
            print("✓ document_shares 表创建成功")
            logger.info("document_shares 表创建成功")
            
            # 验证表结构
            verify_sql = text("""
                SELECT column_name, data_type 
                FROM information_schema.columns 
                WHERE table_name = 'document_shares'
                ORDER BY ordinal_position
            """)
            result = conn.execute(verify_sql)
            
            print("\n表结构:")
            for row in result:
                print(f"  {row[0]:<20} {row[1]}")
            
            print("\n✅ 完成！")
            
    except Exception as e:
        print(f"❌ 创建表失败: {e}")
        logger.error(f"创建表失败: {e}")
        import traceback
        logger.error(traceback.format_exc())
        raise


if __name__ == "__main__":
    try:
        create_document_shares_table()
    except Exception as e:
        print(f"\n错误: {e}")
        sys.exit(1)

